import React, {useEffect, useState} from 'react'
import {
  Form,
  Button,
  DatePicker,
  Input,
  Modal,
  Radio,
  Select,
  Steps,
  Row,
  Col,
  TreeSelect,
  Descriptions,
  Card
} from 'antd'
import {
  channelList,
  jobLevelTypeList,
  socialTraineeStateArray,
  degreeList,
  reinstateList,
  yesOrNoIntList,
  employeeStatusList, genderList, laborContractYearsList, employeeTypeList, maritalList, nationList,websiteList
} from '@/utils/constant'
import {isNewOrReinstate, getJobByOrgId,findTiaoxinTixiByJobId,getContractSubjectList} from '../../service'
import {findItemByTree} from '@/utils/functions'
import {checkIdCard,checkGender,getBirthday} from '@/utils/utils'

import moment from 'moment'
import {connect} from 'umi'

const FormItem = Form.Item
const {Step} = Steps
const {Option} = Select
const RadioGroup = Radio.Group

const formLayout = {
  labelCol: {span: 7},
}

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
}

const CreateForm = (props) => {

  const {visible, onSubmit, onCancel, currentUser, global = {}} = props
  const {options = {}} = global
  const {orgTree = [], orgLine = [], orgSystem = [], jobLevel = []} = options
  const [istx,setIstx] = useState(true);
  const [contractData,setContractData] = useState([]);
  const [employerCompany,setEmployerCompany] = useState(null);

  const [form] = Form.useForm()

  const [formVals, setFormVals] = useState({
    socialTrainee: '0',
    principal: currentUser.name,
    id: props.values.id,
  });

  useEffect(() => {
    //获取合同主体
    getContractSubjectList().then(res => {
      setContractData(res);
    });
  }, []);

  const [currentStep, setCurrentStep] = useState(0)
  const [searchText, setSearchText] = useState('')
  const [searchInfo, setSearchInfo] = useState({})
  const [reinstateType, setReinstateType] = useState(0) // 0:新员工,1：复职员工,2：旧员工,3：在职
  const [searchLoading, setSearchLoading] = useState(false)
  const [unitTree, setUnitTree] = useState([])
  const [jobList, setJobList] = useState([])
  const [jobSelectLevel, setJobSelectLevel] = useState(jobLevel)
  const [socialTrainee,setSocialTrainee] = useState(true)
  const [isDisabled,setIsDisabled] = useState(false)
  const [oid,setOid] = useState(null)
  const [type,setType] = useState(null);
  const [submitting,setSubmitting] = useState(false);


  const getEnterpriseNatureInfo = (value,option) =>{
    setEmployerCompany(option.children);
  };

  const search = async () => {
    const fieldsValue = await form.validateFields()
    const { idCard } = fieldsValue
    if (checkIdCard(idCard)) {
      setSearchText(`该身份证号码格式错误，请重新输入！`)
      setReinstateType(3)
      return
    }
    setSearchLoading(true)
    isNewOrReinstate(idCard).then((res) => {
      setSearchLoading(false)
      setType(res === null ? 0:res.type)
      if (res) {
        if (res.type === 3) {
          setSearchText(`该员工存在归档记录，归档次数为${res.archiveNum}，最近归档日期${moment(res.archiveTime).format('YYYY-MM-DD')}`)
          setReinstateType(2)
          const item = findItemByTree(orgTree, parseInt(res.orgId))
          setUnitTree(item ? item.children : [])
          onChangeUnitId(parseInt(res.unitId))
          form.setFieldsValue({
            ...res, orgId: res.orgId ? parseInt(res.orgId) : undefined,
            unitId: res.unitId ? parseInt(res.unitId) : undefined, hiredate: null
          })
        } else if (['3', '4', '5', '6'].indexOf(res.employeestatus) > -1) {
          //离职员工
          const years = res.daysBetween / 365
          if (years >= 1) {
            setSearchText(`工号${res.code}，姓名${res.name}，入职日期为${moment(res.oldhiredate).format('YYYY-MM-DD')}，离职日期${moment(res.dimissiondate).format('YYYY-MM-DD')}，离职周期超过一年`)
            setReinstateType(2)
          } else {
            setSearchText(`工号${res.code}，姓名${res.name}，入职日期为${moment(res.oldhiredate).format('YYYY-MM-DD')}，离职日期${moment(res.dimissiondate).format('YYYY-MM-DD')}，离职周期不到一年`)
            setReinstateType(1)
          }
          form.setFieldsValue({ idcard: res.idCard, name: res.name,code:res.code })
        } else if (res.type === 0) {
          setSearchText(`姓名${res.name}，目前此员工已经在招聘流程`)
          setReinstateType(3)
        } else if (res.type === 9 && res.dimissiondate) {
          // 曾经实习生，已经离职
          setSearchText(`姓名${res.name}，该员工曾经实习，入职日期为${moment(res.oldhiredate).format('YYYY-MM-DD')}，离职日期${moment(res.dimissiondate).format('YYYY-MM-DD')}`)
          setReinstateType(2)
        } else if (res.type === 9) {
          // 在职实习生
          setSearchText(`姓名${res.name}，该员工正在实习，入职日期为${moment(res.oldhiredate).format('YYYY-MM-DD')}，如需转正式员工，需先发起实习离职流程。`)
          setReinstateType(3)
        } else {
          // 在职员工
          setSearchText(`工号${res.code}，姓名${res.name}，入职日期为${moment(res.oldhiredate).format('YYYY-MM-DD')}，目前此员工在职`)
          setReinstateType(3)
        }
        setSearchInfo(res)
        setOid(res.oid)
      } else {
        setSearchInfo({})
        setSearchText('无此人员历史信息，可以新建')
        setReinstateType(0)
      }
    })
  }

  const onFormCancel = () => {
    form.resetFields()
    onCancel()
    setCurrentStep(0)
    setSearchText('')
  }

  const forward = async () => {
    const fieldsValue = await form.validateFields()
    const {socialTrainee} = fieldsValue
    setCurrentStep(currentStep + 1)
  }

  const backward = () =>{
    form.resetFields()
    setSearchText('')
    setCurrentStep(currentStep - 1)
  }

  const handleNext = async () => {
    const fieldsValue = await form.validateFields()
    setFormVals({...formVals, ...fieldsValue})
    if (currentStep === 1) {
      const idCard = fieldsValue.idCard
      form.setFieldsValue({name:searchInfo.name,idcard: idCard,gender:checkGender(idCard),privatemail:searchInfo.privatemail,mobile:searchInfo.mobile,birthday:moment(getBirthday(idCard)),probationday:6})
    }
    if(fieldsValue.socialTrainee === "1" || fieldsValue.socialTrainee === "2" || fieldsValue.idCard !== null){
      setSocialTrainee(false);
      setIsDisabled(false)
    }else{
      setIsDisabled(true)
    }
    if (currentStep < 2) {
      await forward()
    } else {
      setSubmitting(true)
      onSubmit({...fieldsValue, isReinstate: reinstateType,oid:oid,type:type,
        oldCompanyId:searchInfo && searchInfo.orgId,
        oldDepartmentId:searchInfo && searchInfo.unitId,
        oldJobId:searchInfo && searchInfo.jobId,
        oldJobLevelType:searchInfo && searchInfo.jobLevelType,
        oldJobLevelId:searchInfo && searchInfo.jobLevelId,
        isUpdate:searchInfo.isUpdate,
        employerCompany:employerCompany
      }).then(()=>{
        form.resetFields();
        setOid(null);
        setCurrentStep(0);
      }).finally(()=>{
        setSubmitting(false)
      });
    }
  }

  const onChangeOrgId = (e) => {
    form.setFieldsValue({ unitId: undefined, jobId: undefined,jobSystemId:undefined,lineId:undefined})
    const item = findItemByTree(orgTree, e)
    setUnitTree(item ? item.children : [])
  }

  const onChangeUnitId = (e) => {
    form.setFieldsValue({ jobId: undefined,jobSystemId:undefined,lineId:undefined})
    getJobByOrgId(e).then((res) => {
      setJobList(res)
    })
  }

  const handleChangeIdCard = (e) => {
    const value = e.target.value
    if(value.length === 18) {
      search()
    }
  }

  const getSetupAndLine = (value) => {
    findTiaoxinTixiByJobId(value).then(res => {
      if(res){
        setIstx(true)
        form.setFieldsValue({jobSystemId:res.C_TIXI,lineId:res.C_TIAOXIAN})
      }else{
        setIstx(false)
      }
    })
  }

  const filterOption = (input, option) => {
    return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  }

  const onChangeJobLevelType = (e) => {
    form.setFieldsValue({ jobLevelId: undefined})
    if (e === 2) {
      setJobSelectLevel(jobLevel.filter(e => e.type === 'CODE_MANAGEMENTRANK').reverse())
    } else {
      setJobSelectLevel(jobLevel.filter(e => e.type === 'CODE_PROFESSIONALRANK').reverse())
    }
  }

  const getBirthdayAndGender = () =>{
    const fieldsValue = form.getFieldValue();
    let idCard = fieldsValue.idcard;
    form.setFieldsValue({gender:checkGender(idCard),birthday:moment(getBirthday(idCard))})
  }

  const renderContent = () => {
    if (currentStep === 1) {
      return (
        <Form.Item label="身份证号:" onChange={handleChangeIdCard} extra={searchText ? '' : '请输入身份证查询此员工是否曾经入职过'}>
          <Row gutter={10}>
            <Col span={16}>
              <Form.Item
                name="idCard"
                noStyle
                rules={[{required: true, message: '请输入身份证号进行查询'}]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Button onClick={search} loading={searchLoading}>搜索</Button>
            </Col>
          </Row>
          <Row gutter={10}>
            <div style={{padding: '12px 4px', fontSize: '14px'}}>{searchText}</div>
          </Row>
        </Form.Item>
      )
    }
    if (currentStep === 2) {
      return (
        <>
          <Row gutter={24}>
            <Col {...colStyle}>
              <FormItem name="principal" label="招聘负责人">
                <Input disabled={true}/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="orgId" label="公司" rules={[
                {
                  required: true,
                  message: '请输入公司',
                },
              ]}>
                <TreeSelect treeData={orgTree} onChange={onChangeOrgId}/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="unitId" label="部门" rules={[
                {
                  required: true,
                  message: '请输入部门',
                },
              ]}>
                <TreeSelect treeData={unitTree} onChange={onChangeUnitId}/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="jobId" label="职位" rules={[
                {
                  required: true,
                  message: '请输入职位',
                },
              ]}>
                <Select placeholder="请选择" showSearch filterOption={filterOption} onChange={getSetupAndLine}>
                  {jobList.map((item, index) => {
                    return (
                      <Option value={`${item.coidassignedjob}`} key={item.coidassignedjob}>
                        {item.cname}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="workAddress" label="工作地点" rules={[
                {
                  required: true,
                  message: '请输入工作地点',
                },
              ]}>
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="name" label="姓名" rules={[
                {
                  required: true,
                  message: '请输入姓名',
                },
              ]}>
                <Input disabled={isDisabled}/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="idcard" label="身份证" rules={[
                {
                  required: true,
                  message: '请输入身份证',
                },
              ]}>
                <Input disabled={socialTrainee} onBlur={getBirthdayAndGender} />
              </FormItem>
            </Col>


            <Col {...colStyle}>
              <FormItem name="privatemail" label="个人电子邮箱" rules={[
                {
                  required: true,
                  message: '请输入电子邮箱',
                },
                ({
                  validator(rule,value) {
                    let pattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
                    if (pattern.test(value)) {
                      return Promise.resolve();
                    }
                    return Promise.reject('邮箱格式错误');
                  },
                })
              ]}>
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="mobile" label="手机"rules={[
                {
                  required: true,
                  message: '请输入身份证',
                },
              ]}>
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem label={'性别'} name="gender"  >
                <Select placeholder="请选择" disabled={!!reinstateType} >
                  {genderList.map((item, index) => {
                    return (
                      <Option value={`${item.value}`} key={item.value}>
                        {item.label}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="birthday" label="员工生日">
                <DatePicker className='widthStyle'/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="hiredate" label="拟入职日期" rules={[{required: true, message: '请输入预计入职日期',}]}>
                <DatePicker className='widthStyle'/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="probationday" label="试用期" rules={[
                {
                  required: true,
                  message: '请选择试用期',
                },
              ]}>
                <Select placeholder="请选择" showSearch filterOption={filterOption}>
                  <Option value={0}>无</Option>
                  <Option value={6}>六个月</Option>
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <Form.Item name="jobLevelType" label="职级类型" rules={[
                {
                  required: true,
                  message: '请选择职级类型',
                },
              ]}>
                <Select placeholder="请选择" showSearch filterOption={filterOption} onChange={onChangeJobLevelType}>
                  {jobLevelTypeList.map((item, index) => {
                    return (
                      <Option value={item.value} key={item.value}>
                        {item.label}
                      </Option>
                    )
                  })}
                </Select>
              </Form.Item>
            </Col>

            <Col {...colStyle}>
              <Form.Item name="jobLevelId" label="职级" rules={[
                {
                  required: true,
                  message: '请选择职级',
                },
              ]}>
                <Select placeholder="请选择" showSearch filterOption={filterOption}>
                  {
                    jobSelectLevel.map((item, index) => {
                      return (
                        <Option value={`${item.id}`} key={item.id}>
                          {item.name}
                        </Option>
                      )
                    })
                  }
                </Select>
              </Form.Item>
            </Col>

            <Col {...colStyle}>
              <FormItem name="socialTrainee" label="招聘类型">
                <Select placeholder="请选择" disabled>
                  {socialTraineeStateArray.map((item, index) => {
                    return (
                      <Option value={`${index}`} key={index}>
                        {item}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="isManagementTrainee" label="是否管培生" rules={[{required: true, message: '是否管培生不能为空'}]}>
                <Select placeholder="请选择">
                  {yesOrNoIntList.map((item, index) => {
                    return (
                      <Option value={item.value} key={item.value}>
                        {item.label}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>


            <Col {...colStyle}>
              <FormItem name="channel" label="招聘渠道" rules={[{required: true, message: '招聘渠道不能为空'}]}>
                <Select placeholder="请选择" showSearch filterOption={filterOption}>
                  {
                    channelList.map((item, index) => {
                      return (
                        <Option value={item.value} key={item.value}>
                          {item.label}
                        </Option>
                      )
                    })
                  }
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="recruitmentWeb" label="招聘网站" rules={[{required: true, message: '招聘网站不能为空'}]}>
                <Select placeholder="请选择" showSearch filterOption={filterOption}>
                  {
                    websiteList.map((item, index) => {
                      return (
                        <Option value={item.value} key={item.value}>
                          {item.label}
                        </Option>
                      )
                    })
                  }
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="innerReferrer" label="推荐人（内部）">
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="outerReferrer" label="推荐人（外部）">
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="jobSystemId" label="体系" rules={[
                {
                  required: true,
                  message: '请选择体系',
                },
              ]}>
                <Select placeholder="请选择" disabled={istx} showSearch filterOption={filterOption}>
                  {orgSystem.map((item, index) => {
                    return (
                      <Option value={`${item.id}`} key={item.id}>
                        {item.name}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="lineId" label="条线" rules={[
                {
                  required: true,
                  message: '请选择条线',
                },
              ]}>
                <Select placeholder="请选择" disabled={istx} showSearch filterOption={filterOption}>
                  {orgLine.map((item, index) => {
                    return (
                      <Option value={`${item.id}`} key={item.id}>
                        {item.name}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="degree" label="最高学历" rules={[{required: true,message: '请选择最高学历'}]}>
                <Select placeholder="请选择">
                  {degreeList.map((item, index) => {
                    return (
                      <Option value={`${item.value}`} key={item.value}>
                        {item.label}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="speciality" label="所学专业" rules={[{required: true,message: '请输入所学专业'}]}>
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="laborContractYears" label="劳动合同期限" rules={[{required: true, message: '劳动合同期限不能为空'}]}>
                <Select placeholder="请选择" showSearch filterOption={filterOption}>
                  {laborContractYearsList.map((item, index) => {
                    return (
                      <Option value={item.value} key={item.value}>
                        {item.label}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="jobType" label="员工类型" rules={[{required: true, message: '员工类型不能为空'}]}>
                <Select placeholder="请选择" showSearch filterOption={filterOption}>
                  {employeeTypeList.map((item, index) => {
                    return (
                      <Option value={`${item.value}`} key={item.value}>
                        {item.label}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem label={'工号'} name="code">
                <Input placeholder="请输入"/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem label={'民族'} name="nationality" rules={[{required: true, message: '民族不能为空'}]}>
                <Select placeholder="请选择" showSearch filterOption={filterOption}>
                  {nationList.map((item, index) => {
                    return (
                      <Option value={`${item.value}`} key={item.value}>
                        {item.label}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem label={'参加工作时间'} name="beginworkdate" rules={[{required: true, message: '参加工作时间不能为空'}]}>
                <DatePicker placeholder="请选择日期" style={{ width: '100%' }}/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem label={'婚姻状况'} name="marital" rules={[{required: true, message: '婚姻状况不能为空'}]}>
                <Select placeholder="请选择">
                  {maritalList.map((item, index) => {
                    return (
                      <Option value={`${item.value}`} key={item.value}>
                        {item.label}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="employerCompanyId" label="甲方主体"  rules={[{required: true, message: '甲方主体不能为空'}]}>
                <Select placeholder="请选择甲方主体"  onChange={getEnterpriseNatureInfo} showSearch filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} allowClear>
                  { contractData.length>0 ? contractData.map((item, index) => {
                    return (
                      <Option value={item.id} key={index} lable={item}>
                        {item.name}
                      </Option>
                    )
                  }) : ''}
                </Select>
              </FormItem>
            </Col>


          </Row>
          {
            searchInfo && searchInfo.name && <Card
              title="复职员工原信息"
              bordered={false}
            >
              <Descriptions>
                <Descriptions.Item label="原公司名称">{searchInfo.orgname}</Descriptions.Item>
                <Descriptions.Item label="原部门名称">{searchInfo.unitname}</Descriptions.Item>
                <Descriptions.Item label="原岗位名称">{searchInfo.jobname}</Descriptions.Item>
                <Descriptions.Item label="原工号">{searchInfo.code}</Descriptions.Item>
                <Descriptions.Item
                  label="员工状态">{employeeStatusList.find(e => searchInfo.employeestatus === e.value)?.label}</Descriptions.Item>
                <Descriptions.Item
                  label="招聘类型">{reinstateList.find(e => searchInfo.type === e.value)?.label}</Descriptions.Item>
                <Descriptions.Item
                  label="原入职日期">{searchInfo.oldhiredate && moment(searchInfo.oldhiredate).format('YYYY-MM-DD')}</Descriptions.Item>
                <Descriptions.Item
                  label="原离职日期">{searchInfo.dimissiondate && moment(searchInfo.dimissiondate).format('YYYY-MM-DD')}</Descriptions.Item>
                <Descriptions.Item label="是否中心负责人">{searchInfo.iscentreprincipal === 0 ? '是' : '否'}</Descriptions.Item>
                <Descriptions.Item
                  label="是否部门负责人">{searchInfo.isdepartmentprincipa === 0 ? '是' : '否'}</Descriptions.Item>
              </Descriptions>
            </Card>
          }
        </>
      )
    }
    return (
      <>
        <FormItem name="socialTrainee" label="招聘类型">
          <RadioGroup>
            {
              socialTraineeStateArray.map((item, index) => {
                return <Radio value={`${index}`} key={index}>{item}</Radio>
              })
            }
          </RadioGroup>
        </FormItem>
      </>
    )
  }

  const renderFooter = () => {
    if (currentStep === 1) {
      return (
        <>
          <Button style={{float: 'left'}} onClick={backward}>
            上一步
          </Button>
          <Button onClick={() => onFormCancel()}>取消</Button>
          <Button disabled={!searchText || reinstateType === 3} type="primary" onClick={() => handleNext()}>
            下一步
          </Button>
        </>
      )
    }
    if (currentStep === 2) {
      return (
        <>
          <Button style={{float: 'left'}} onClick={backward}>
            上一步
          </Button>
          <Button onClick={() => onFormCancel()}>取消</Button>
          <Button type="primary" onClick={() => handleNext()} loading={submitting}>
            完成
          </Button>
        </>
      )
    }
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleNext()}>
          下一步
        </Button>
      </>
    )
  }

  return (
    <Modal
      width={1280}
      destroyOnClose
      title="新建"
      visible={visible}
      footer={renderFooter()}
      onOk={handleNext}
      onCancel={onFormCancel}
      okText="确认"
      cancelText="取消"
    >
      <Steps style={{marginBottom: 28, padding: '0 290px'}} current={currentStep}>
        <Step title="招聘类型"/>
        <Step title="信息检索"/>
        <Step title="基础信息"/>
      </Steps>
      <Form
        {...formLayout}
        form={form}
        initialValues={{
          socialTrainee: formVals.socialTrainee,
          principal: formVals.principal,
          id: formVals.id,
        }}
        style={{paddingTop: '24px'}}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}

// export default CreateForm

export default connect(({user, global}) => ({
  global,
  currentUser: user.currentUser,
}))(CreateForm)
